# coding: utf-8
from xml.etree import ElementTree


class FormatXmlArray(object):
    @classmethod
    def xml_to_array(cls, xml):
        """
        将xml转为array
        :param xml:
        :return:
        """
        array_data = {}
        root = ElementTree.fromstring(xml)
        for child in root:
            value = child.text
            array_data[child.tag] = value
        return array_data

    @classmethod
    def array_to_xml(cls, array):
        """
        将array 转换成 xml 格式
        :param array:
        :return:
        """
        xml = ["<xml>"]
        for k, v in array.items():
            if v.isdigit():
                xml.append("<{0}>{1}</{0}>".format(k, v))
            else:
                xml.append("<{0}><![CDATA[{1}]]></{0}>".format(k, v))
        xml.append("</xml>")
        return "".join(xml)
